//
//  BZMeViewController.m
//  BZMeComponent
//
//  Created by 郭艺伟 on 2017/10/11.
//  Copyright © 2017年 郭艺伟. All rights reserved.
//

#import "BZMeViewController.h"
#import "BZMeUserInfo.h"
#import "BZMeHeaderView.h"
#import <BZPreHeaderComponent/BZCommonHeader.h>
#import <libextobjc/EXTScope.h>
#import <Masonry/Masonry.h>
#import <SDWebImage/UIImageView+WebCache.h>
#import "BZMeService.h"
#import <BZBundleKit/BZImageKit.h>

@interface BZMeViewController ()<UITableViewDelegate,UITableViewDataSource,BZMeHeaderViewDelegate>


@property (nonatomic, copy  ) NSArray           *data;

@property (nonatomic, weak  ) UITableView       *userProfileV;

@property (nonatomic, strong) BZMeUserInfo       *userInfo;

@property (nonatomic, strong) NSDateFormatter   *fmt;

@property (nonatomic, strong) BZMeHeaderView    *header;

@property (nonatomic, strong) UIButton          *btnNavRight;

@end

@implementation BZMeViewController

- (BZMeHeaderView *)header{
    
    if (!_header) {
        _header = [[BZMeHeaderView alloc] init];
        _header.delegate = self;
    }
    return _header;
}

- (NSDateFormatter *)fmt{
    
    if (!_fmt) {
        
        _fmt = [[NSDateFormatter alloc] init];
        [_fmt setDateFormat:@"yyyy-MM-dd"];
    }
    
    return _fmt;
}


- (BZMeUserInfo *)userInfo{
    
    if (!_userInfo) {
        
        _userInfo = [[BZMeUserInfo alloc] init];
    }
    return _userInfo;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title    = @"个人中心";
    self.view.backgroundColor    = COLOR(244, 244, 244, 1.0);
    UITableView *userProfileV    = [[UITableView alloc]init];
    userProfileV.tableFooterView = [[UIView alloc]init];
    userProfileV.delegate        =  self;
    userProfileV.dataSource      =  self;
    
    userProfileV.backgroundColor = COLOR(244, 244, 244, 1.0);
    [userProfileV registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.view addSubview: userProfileV];
    self.userProfileV = userProfileV;
    @weakify(self)
    [userProfileV mas_makeConstraints:^(MASConstraintMaker *make) {
        @strongify(self);
        make.left.equalTo(self.view.mas_left).with.offset(0);
        make.right.equalTo(self.view.mas_right).with.offset(0);
        make.top.equalTo(self.view.mas_top).with.offset(0);
        make.bottom.equalTo(self.view.mas_bottom).with.offset(0);
    }];
    
    self.data = @[@"个人资料",@"我的帮助",@"设置",@"消息中心"];
    
    
    //[ZZFBaseInfoService shareInstance];//初始化基础信息类获取信息
    
    //    [self requestUserInfo];
    
    
}


//- (UIButton *)btnNavRight{
//    
//    if (!_btnNavRight) {
//        UIButton* btn  = [UIButton buttonWithType:UIButtonTypeCustom];
//        [btn  addTarget:self action:@selector(_jumpLevel) forControlEvents:UIControlEventTouchUpInside];
//        [btn  setTitleEdgeInsets:UIEdgeInsetsMake(0, 2, 0, 0)];
//        [btn  setImage:[UIImage imageNamed:@"btn_consciousmind"] forState:UIControlStateNormal];
//        [btn.titleLabel  setFont:SystemFont(12)];
//        [btn  setTitleColor:RGB_Brown];
//        _btnNavRight = btn;
//    }
//    
//    return _btnNavRight;
//}


- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    [self requestUserInfo];
    
//    ZZFUserModel *userModel = [ZZFDataBaseManager queryCurrentLoginUserWithError:nil];
//
//    if (userModel.customerId != self.userInfo.customerId) {
//        
//        [self requestUserInfo];
//    }
//    
//    [self.userProfileV reloadData];
//    if (self.userInfo) {
//        [self.btnNavRight  setTitle:[NSString stringWithFormat:@"%ld",self.userInfo.point] forState:UIControlStateNormal];
//    }
}



- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 236;
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    return [self tableviewHeader];
    
}

- (void)requestUserInfo{
    
    BZMeService *meService = [[BZMeService alloc]init];
    @weakify(self);
    [meService getCurrentUserInfoSuccess:^(NSString *code, id responseObject) {
        @strongify(self);
        NSLog(@"responseObject = %@",responseObject);
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            
            NSError *error = nil;
            self.userInfo = [MTLJSONAdapter modelOfClass:[BZMeUserInfo class]
                                      fromJSONDictionary:responseObject
                                                   error:&error];
            //self.userInfo.customerId = userModel.customerId;
            [self transfomerResponseToModel:responseObject];
            
            /*[ZZFDataBaseManager updateDataBaseByUserInfoModelAsync:self.userInfo
                                                           success:nil
                                                           failure:nil];*/
            [self.userProfileV reloadData];
        }
        
    } failure:^(NSString *code, NSError *error) {
        
    }];
}



- (void)transfomerResponseToModel:(NSDictionary *)responseObject{
    
    self.userInfo.nickname   = [[responseObject objectForKey:@"nickname"]length]?[responseObject objectForKey:@"nickname"]:@"未设置";
    self.userInfo.portrait   = [responseObject objectForKey:@"portrait"];
    self.userInfo.qrCode     = [responseObject objectForKey:@"qrCode"];
    self.userInfo.customerNo = [[responseObject objectForKey:@"customerNo"] length]?[responseObject objectForKey:@"customerNo"]:@"未设置";
    self.userInfo.sex        = [[responseObject objectForKey:@"sex"]length]?[responseObject objectForKey:@"sex"]:@"未设置";
    self.userInfo.sectName   = [[responseObject objectForKey:@"sectName"]length]?[responseObject objectForKey:@"sectName"]:@"未设置";
    self.userInfo.sign       = [[responseObject objectForKey:@"sign"] length]?[responseObject objectForKey:@"sign"]:@"未设置";
    self.userInfo.address    = [[responseObject objectForKey:@"address"]length]?[responseObject objectForKey:@"address"]:@"未设置";
    self.userInfo.sectId     = [[responseObject objectForKey:@"sectId"]integerValue];
    self.userInfo.profession = [[responseObject objectForKey:@"profession"]length]?[responseObject objectForKey:@"profession"]:@"未设置";
    self.userInfo.interest   = [[responseObject objectForKey:@"interest"] length]?[responseObject objectForKey:@"interest"]:@"未设置";
    self.userInfo.address    = [[responseObject objectForKey:@"address"] length]?[responseObject objectForKey:@"address"]:@"未设置";
    self.userInfo.rankName   = [responseObject objectForKey:@"rankName"];
    self.userInfo.rankGrade  = [[responseObject objectForKey:@"grade"]integerValue];
    self.userInfo.point      = [[responseObject objectForKey:@"point"]integerValue];
    [self.btnNavRight  setTitle:[NSString stringWithFormat:@"%ld",self.userInfo.point] forState:UIControlStateNormal];
    [self.btnNavRight  sizeToFit];
    //self.btnNavRight.width+=[UIView autoValue:8];
    
    UInt64 birth             = [[responseObject objectForKey:@"birth"] longLongValue];
    if (birth >1000000000) {
        birth = birth/1000;
    }
    if (birth) {
        self.userInfo.birth      = [self.fmt stringFromDate:[NSDate dateWithTimeIntervalSince1970:birth]];
    }else{
        self.userInfo.birth      = @"未设置";
    }
    
    self.userInfo.identity   = [[responseObject objectForKey:@"customerTypeName"] length]?[responseObject objectForKey:@"customerTypeName"]:@"未设置";
    
}


- (UIView *)tableviewHeader{
    
    
    NSString *buddhalName = [NSString stringWithFormat:@"%@:%@",@"佛友号",self.userInfo.customerNo?:@"未设置"];
    self.header.buddhalNameL.text = buddhalName;
    self.header.nickL.text = self.userInfo.nickname;
    [self.header updateNickNameConstrains];
    if ([[NSFileManager defaultManager]fileExistsAtPath:self.userInfo.avatarLocal]) {
        self.header.avartarV.image = [UIImage imageWithContentsOfFile:self.userInfo.avatarLocal];
    }else{
        
        [self.header.avartarV sd_setImageWithURL:[NSURL URLWithString:self.userInfo.portrait]
                                placeholderImage:[UIImage imageNamed:@"icon_head"]
                                       completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                                           NSLog(@"error = %@--->头像获取失败!",error);
                                       }];
    }
    self.header.rankL.text = [NSString stringWithFormat:@"LV.%lu %@",(unsigned long)self.userInfo.rankGrade,self.userInfo.rankName];
    return self.header;
}

- (void)back{
    
    NSLog(@"back");
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

#pragma mark --TableView Datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return [self.data count];
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    NSString *string = self.data[indexPath.row];
    cell.textLabel.text = string;
    
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            [cell.imageView setImage:[BZImageKit imageWithName:@"icon_personinfo" type:@"png" inBundle:@"BZResourcesBundle" inDirectory:@"ios/Me"]];
        }else if (indexPath.row == 1){
            
            [cell.imageView setImage:[BZImageKit imageWithName:@"icon_help" type:@"png" inBundle:@"BZResourcesBundle" inDirectory:@"ios/Me"]];
        }else if (indexPath.row == 2){
            
            [cell.imageView setImage:[BZImageKit imageWithName:@"icon_set" type:@"png" inBundle:@"BZResourcesBundle" inDirectory:@"ios/Me"]];
        }else if (indexPath.row == 3){
            
            [cell.imageView setImage:[BZImageKit imageWithName:@"icon_infocenter" type:@"png" inBundle:@"BZResourcesBundle" inDirectory:@"ios/Me"]];
        }
    }
    
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    return  cell;
    
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 49;
    
}



#pragma mark ----TableView Delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    /*
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [tableView deselectRowAtIndexPath:indexPath animated:NO];
    });
    
    
    if (indexPath.row == 0) {
        
        ZZFUserProfileVC *userProfileVC = [[ZZFUserProfileVC alloc]init];
        userProfileVC.title = @"个人资料";
        userProfileVC.userInfo = self.userInfo;
        @weakify(self);
        userProfileVC.userInfoCallBack = ^(ZZFUserInfo *userInfo){
            @strongify(self);
            self.userInfo = userInfo;
            [self.userProfileV reloadData];
        };
        [self.navigationController pushViewController:userProfileVC animated:YES];
        
    }else if (indexPath.row == 1){
        
        // ZZFUserSetterController *userSetter = [[ZZFUserSetterController alloc]init];
        //userSetter.title = @"我的帮助";
        //[self.navigationController pushViewController:userSetter animated:YES];
        ZZFQiuZuMainController* vc = [ZZFQiuZuMainController new];
        [self  commonPushVcWithAni:vc];
        
    }else if (indexPath.row == 2){
        
        ZZFSettingVC *userSetter = [[ZZFSettingVC alloc]init];
        userSetter.title = @"设置";
        [self.navigationController pushViewController:userSetter animated:YES];
        
        
    }else if ( indexPath.row == 3){
        
        ZZFSettingInfoCenterVC *settingInfo = [[ZZFSettingInfoCenterVC alloc]init];
        settingInfo.title = @"消息中心";
        [self.navigationController pushViewController:settingInfo animated:YES];
        
    }else{
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = @"程序GG,正在努力开发中！";
        [hud hide:YES afterDelay:1.0];
    }*/
    
}



//- (void)didClickAvatarFromView:(ZZFView *)headerV{
//    
////    ZZFLog(@"did click avatar!!!");
////    
////    ZZFUserProfileVC *userProfileVC = [[ZZFUserProfileVC alloc]init];
////    userProfileVC.title = @"个人资料";
////    userProfileVC.userInfo = self.userInfo;
////    @weakify(self);
////    userProfileVC.userInfoCallBack = ^(ZZFUserInfo *userInfo){
////        @strongify(self);
////        self.userInfo = userInfo;
////        [self.userProfileV reloadData];
////    };
////    [self.navigationController pushViewController:userProfileVC animated:YES];
//    
//}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


@end
